package com.asm.rpc;

import com.asm.handler.RpcResponseMessageHandler;
import com.asm.message.RpcRequestMessage;
import com.asm.protocol.MessageCodecSharable;
import com.asm.protocol.ProcotolFrameDecoder;
import com.asm.protocol.SequencedGenerator;
import com.asm.rpc.service.HelloService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Proxy;

@Slf4j
public class RpcClientManager {
    public static void main(String[] args) {
        HelloService service=getProxyService(HelloService.class);
        System.out.println(service.sayHello("张三"));
        System.out.println(service.sayHello("李四"));
        System.out.println(service.sayHello("王五"));
    }
    //创建代理类

    public static <T> T getProxyService(Class<T> serviceClass){
        //通过类型拿到类加载器
        ClassLoader loader = serviceClass.getClassLoader();
        //代理要实现的接口数组
       Class<?>[] interfaces=new Class[]{serviceClass};

        /**
         * @param loader 类加载器
         * @param interfaces 代理要实现的接口数组
         * @param (proxy,method,args)   决定了代理类、代理方法要调用的行为
         * */                                                      //sayHello
        Object o = Proxy.newProxyInstance(loader, interfaces, (proxy, method, args) -> {
            //1.将方法调用转换为消息对象
            int sequenceId = SequencedGenerator.nextId();
            RpcRequestMessage message = new RpcRequestMessage(
                    sequenceId,//序列ID,不重复的，不考虑分布式
                    serviceClass.getName(), //对象类名
                    method.getName(),  //方法名称
                    method.getReturnType(),   //返回值类型
                    method.getParameterTypes(),  //方法的参数类型
                    args   //实际参数值
            );
            //2.将消息对象发送出去
            getChannel().writeAndFlush(message);
             //3.准备一个空Promise对象，来接收结果线程,谁发的谁来接收       指定promise对象异步接收结果线程
            DefaultPromise<Object>promise=new DefaultPromise<>(getChannel().eventLoop());
            RpcResponseMessageHandler.PROMISE.put(sequenceId,promise);

            //3.等待promise结果
            promise.await();
            //4.等promise里面有结果
             if(promise.isSuccess()){
                 //把正确结果拿出来。
               return   promise.getNow();
             }
             else {
                 //拿到异常信息
                 throw new RuntimeException(promise.cause());
             }


        });
        return (T)o;
    }



    private static Channel channel = null;
   private static final Object LOCK=new Object();


   //获取唯一的channel对象
    public static Channel getChannel() {
           if(channel!=null){
               return channel;
           }

           //排队进入
           synchronized (LOCK){
               if(channel!=null){
                   return channel;
               }
           }
           initChannel();
           return channel;

    }

    //初始化channel
    private static void initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler();
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //rpc请求消息处理器，待实现
        RpcResponseMessageHandler RPC_HANDLER = new RpcResponseMessageHandler();


        Bootstrap bootstrap = new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.group(group);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast(new ProcotolFrameDecoder());
             //   ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                ch.pipeline().addLast(RPC_HANDLER);
            }
        });
        try {
            channel = bootstrap.connect("localhost", 8080).sync().channel();


            channel.closeFuture().addListener(future -> {
                group.shutdownGracefully();
            });
        } catch (InterruptedException e) {
            log.error("client err", e);
        }
    }
}
